from django.shortcuts import render

import json

from django.http import JsonResponse
from django.core.exceptions import ObjectDoesNotExist

from api.utils import  success_response_with_data, failed_response_with_data, list_response
from api.models import Requirement
from api.serializers import RequirementSerializer

from rest_framework import viewsets
from drf_yasg2.utils import swagger_auto_schema
from drf_yasg2 import openapi
from rest_framework.decorators import action

from api.mylogger import logger


class RequirementViewSet(viewsets.ModelViewSet):
    table_name = Requirement._meta.db_table
    serializer_class = RequirementSerializer

    request_body = openapi.Schema(type=openapi.TYPE_OBJECT,
                                  required=['desc'],
                                  properties={
                                      "desc": openapi.Schema(type=openapi.TYPE_STRING, description="需求描述"),
                                      "client_type": openapi.Schema(type=openapi.TYPE_STRING, description="客户类别"),
                                      "company_name": openapi.Schema(type=openapi.TYPE_STRING, description="公司"),
                                      "contact_name": openapi.Schema(type=openapi.TYPE_STRING,description="联系人"),
                                      "contact_mobile": openapi.Schema(type=openapi.TYPE_STRING, description="手机"),
                                      "contact_email": openapi.Schema(type=openapi.TYPE_STRING, description="邮箱"),
                                      "status": openapi.Schema(type=openapi.TYPE_INTEGER, description="状态"),
                                      "answer_content": openapi.Schema(type=openapi.TYPE_STRING, description="回复内容"),
                                      "answer_name": openapi.Schema(type=openapi.TYPE_STRING, description="回复人姓名"),
                                  }, )

    @swagger_auto_schema(operation_id='添加需求', tags=['requirement'], request_body=request_body)
    @action(methods=['POST'], detail=False)
    def requirement_add(self, request):
        data = json.loads(request.body.decode('utf8'))
        serializer = RequirementSerializer(data=data)
        if serializer.is_valid():
            res = serializer.save()
            res_data = {
                "table_name": self.table_name,
                "id": res.id,
            }
            return success_response_with_data(res_data, msg="新增需求成功")
        return JsonResponse(serializer.errors, status=400)

    request_body_mod = openapi.Schema(type=openapi.TYPE_OBJECT,
                                      required=['id', 'desc'],
                                      properties={
                                          "id": openapi.Schema(type=openapi.TYPE_INTEGER, description="内部Id"),
                                          "desc": openapi.Schema(type=openapi.TYPE_STRING, description="需求描述"),
                                          "client_type": openapi.Schema(type=openapi.TYPE_STRING, description="客户类别"),
                                          "company_name": openapi.Schema(type=openapi.TYPE_STRING, description="公司"),
                                          "contact_name": openapi.Schema(type=openapi.TYPE_STRING,description="联系人"),
                                          "contact_mobile": openapi.Schema(type=openapi.TYPE_STRING, description="手机"),
                                          "contact_email": openapi.Schema(type=openapi.TYPE_STRING, description="邮箱"),
                                          "status": openapi.Schema(type=openapi.TYPE_INTEGER, description="状态"),
                                          "answer_content": openapi.Schema(type=openapi.TYPE_STRING, description="回复内容"),
                                          "answer_name": openapi.Schema(type=openapi.TYPE_STRING, description="回复人姓名"),
                                      }, )

    @swagger_auto_schema(operation_id='修改需求', tags=['requirement'], request_body=request_body_mod)
    @action(methods=['POST'], detail=False)
    def requirement_mod(self, request):
        data = json.loads(request.body.decode('utf8'))
        db_id = data.get('id', None)
        if db_id is None:
            return failed_response_with_data(msg="没有id, 修改不了")

        serializer = RequirementSerializer(data=data)
        if serializer.is_valid():
            try:
                db_ret = serializer.update(instance=Requirement.objects.get(id=db_id), validated_data=data)
                res_data = {
                    "table_name": self.table_name,
                    "id": db_ret.id
                }
                return success_response_with_data(res_data, msg="修改需求成功!")
            except ObjectDoesNotExist:
                logger.debug("没有修改记录")
                return failed_response_with_data(msg=self.table_name+f"没有被修改,未发现id为{db_id}的记录")
        return JsonResponse(serializer.errors, status=400)

    @swagger_auto_schema(operation_id='删除需求', tags=['requirement'], request_body=openapi.Schema(
        type=openapi.TYPE_OBJECT,
        properties={
            "id": openapi.Schema(type=openapi.TYPE_INTEGER, description="需求的内部Id"),
        },
    ))
    @action(methods=['POST'], detail=False)
    def requirement_del(self, request):
        data = json.loads(request.body.decode('utf8'))
        db_id = data.get('id', None)
        # qry = Material.objects.filter(id=db_id)
        # print(qry.query)
        deleted_cnt, _ = Requirement.objects.filter(id=db_id).delete()
        res_data = {
            "table_name": self.table_name,
            "id": db_id,
            "rows_deleted": deleted_cnt,
            "info": "删除" + str(deleted_cnt) + "条记录!",
        }
        return success_response_with_data(res_data, msg="删除需求记录成功!")

    @swagger_auto_schema(operation_id='单个需求信息', tags=['requirement'], request_body=openapi.Schema(
        type=openapi.TYPE_OBJECT,
        properties={
            "id": openapi.Schema(type=openapi.TYPE_INTEGER, description="需求的内部Id"),
        },
    ))
    @action(methods=['POST'], detail=False)
    def requirement_one(self, request):
        data = json.loads(request.body.decode('utf8'))
        db_id = data.get('id', None)
        try:
            qry = Requirement.objects.get(id=db_id)
            serializer = RequirementSerializer(qry)
            return success_response_with_data(serializer.data, msg=self.table_name + "查询单个需求成功!")
        except ObjectDoesNotExist:
            logger.debug("没有发现记录")
            return failed_response_with_data(None, msg=self.table_name + f"未查到id为{db_id}的需求!")

    @swagger_auto_schema(operation_id='需求列表查询', tags=['requirement'],
                         method='POST',
                         request_body=openapi.Schema(
                             type=openapi.TYPE_OBJECT,
                             properties={
                                 "query": openapi.Schema(type=openapi.TYPE_STRING, description="名称的部分信息"),
                             },
                         )
                         )
    @swagger_auto_schema(operation_id='需求列表查询GET', tags=['requirement'],
                         method='GET',
                         manual_parameters=[
                             openapi.Parameter(name='query', in_=openapi.IN_QUERY, type=openapi.TYPE_STRING,
                                               description='名称的部分信息')
                         ]
                         )
    @action(methods=['POST', 'GET'], detail=False)
    def requirement_list(self, request):
        if request.method == 'POST':
            data = json.loads(request.body.decode('utf8'))
            current_page = data.get("pagenum", 1)
            page_size = data.get("pagesize", 10)
            query = data.get("query", '')

        if request.method == 'GET':
            current_page = request.GET.get("pagenum", 1)
            page_size = request.GET.get("pagesize", 10)
            query = request.GET.get("query", '')

        if current_page < 1:
            current_page = 1
        # 为避免大数据量，用这种方式比较合适，不要用Paginator
        start_row = (current_page - 1) * page_size
        end_row = current_page * page_size

        try:
            objects = Requirement.objects
            if len(query):
                objects = objects.filter(name__icontains=query)
            objects = objects.all()
            total = objects.count()
            rows = objects[start_row:end_row]
            logger.debug(f"rows.query {rows.query}")

        except ObjectDoesNotExist:
            logger.debug("没有发现记录")
            return list_response()

        serializer = RequirementSerializer(rows, many=True)

        return list_response(serializer.data, total, page_size, current_page, self.table_name)
